#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include "logger.h"
#include "netconnect.h"
#include "sql.h"
#include "temper.h"

#define SENSOR_READ_INTERVAL 10  // 传感器读取间隔(秒)
#define DB_PATH "temper.db"      // 数据库文件路径
//断联重连部分
#define MAX_RECONNECT_ATTEMPTS 50 // 最大重连尝试次数
#define RECONNECT_INTERVAL 5     // 重连间隔(秒)

int  sample_flag = 0;
int  rv_temp = -1;
int  rv_humidity = -1;
int  net_status;
int  reconnect_attempts = 0;


//上传未上传数据部分
void upload_pending_data() {
    SensorData unuploaded[10];
    int count = sql_get_unuploaded(unuploaded, 10);
    
    for (int i = 0; i < count; i++) {
        if (network_send(&net_ctx, &unuploaded[i]) == 0) {
            log_info("Data sent successfully: ID=%d", unuploaded[i].id);
            if (sql_mark_uploaded(unuploaded[i].id) == 0) {
                log_debug("Marked data as uploaded: ID=%d", unuploaded[i].id);
            } else {
                log_error("Failed to mark data as uploaded: ID=%d", unuploaded[i].id);
            }
        } else {
            log_error("Failed to send data: ID=%d", unuploaded[i].id);
        }
    }
}


int main() {
    // 初始化系统
    if (log_open("client.log", LOG_LEVEL_INFO, 1024, LOG_LOCK_ENABLE) < 0) {
        fprintf(stderr, "Failed to initialize logger\n");
        return -1;
    }
    
    if (sql_init_db(DB_PATH) < 0) {
        log_error("DB init failed");
        return -1;
    }

    network_init(&net_ctx);
    
    // 初始网络连接
    if (network_connect(&net_ctx, MAX_RECONNECT_ATTEMPTS, RECONNECT_INTERVAL) != NET_CONNECTED) {
        log_warning("Initial network connection failed");
    }

    log_info("Client application started");

    while (1) {
        SensorData sensor_data;
        time_t cycle_start = time(NULL);
        
        // 采样传感器数据
        rv_temp = get_temperature(&sensor_data.temperature);
        rv_humidity = get_humidity(&sensor_data.humidity);
        sample_flag = (rv_temp == 0 && rv_humidity == 0) ? 1 : 0;

        // 记录日志
        if (rv_temp < 0) {
            log_error("Temperature reading failed, error: %d", rv_temp);
        } else {
            log_info("Temperature: %.2f°C", sensor_data.temperature);
        }
        
        if (rv_humidity < 0) {
            log_error("Humidity reading failed, error: %d", rv_humidity);
        } else {
            log_info("Humidity: %.1f%%", sensor_data.humidity);
        }
        
        // 检查网络状态
        if (network_check(&net_ctx) != NET_CONNECTED) {
            log_info("Network disconnected, attempting to reconnect...");
            network_connect(&net_ctx, MAX_RECONNECT_ATTEMPTS, RECONNECT_INTERVAL);
            
            // 存储数据到数据库
            if (sample_flag) {
                strcpy(sensor_data.sensor_id, "default_sensor");
                sensor_data.uploaded = false;
                sql_insert_data(&sensor_data);
            }
        } else {
            // 网络连接成功 - 发送数据
            if (sample_flag && network_send(&net_ctx, &sensor_data) < 0) {
                strcpy(sensor_data.sensor_id, "default_sensor");
                sensor_data.uploaded = false;
                sql_insert_data(&sensor_data);
            }
            
            // 发送未上传的数据
            upload_pending_data();
        }
        
        // 清理旧数据
        sql_delete_old_data(3);

        // 确保是十秒的间隔
        time_t elapsed = time(NULL) - cycle_start;
        if (elapsed < SENSOR_READ_INTERVAL) {
            sleep(SENSOR_READ_INTERVAL - elapsed);
        } else {
            log_warning("Cycle overrun by %ld seconds", elapsed - SENSOR_READ_INTERVAL);
        }
    }

    network_close(&net_ctx);
    sql_close_db();
    log_close();
    return 0;
}